<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <div class="about-master-container">
      <b-steps
        :current="stepVal"
        direction="vertical"
        @change.self="stepChange"
      >
        <b-step title="基本信息">
          <a-card v-loading="loading" v-show="activeKey[0]">
            <title-name title="基本信息" />
            <BForm
              ref="form"
              :config="formConfig"
              :form="form"
              :rule="formRules"
            />
            <div v-if="!isAudit" style="text-align:right;">
              <a-button
                v-if="!disabled" type="primary" :loading="saveLoading" :disabled="submitLoading" class="mr10p"
                @click="save('DRAFT',false,)"
              >
                保存草稿
              </a-button>
              <a-button type="primary" :loading="saveLoading" :disabled="submitLoading" class="mr10p"
                        @click="save('DRAFT',false,true)"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="混凝土需用明细">
          <a-card v-if="activeKey[1]">
            <materialDetail
              :disabled="disabled"
              :materialMonthId="form.materialMonthId"
              :id="form.id"
            />
            <div v-if="!isAudit" style="text-align:right;">
              <a-button type="primary" @click="stepChange(stepVal + 1)">下一步</a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card v-if="activeKey[2]">
            <u-table
              :is-show="!disabled"
              :upload-list="Api.addFile()"
              :delete-url="Api.deleteFile()"
              :list-url="Api.findFileList()"
              :business-id="form.id"
              business-code="MM20"
            />
          </a-card>
        </b-step>
      </b-steps>
      <div v-if="!isConsultation" class="tar page-btn-right-top">
        <template v-if="!disabled && !isAudit">
          <a-button type="primary" :loading="submitLoading" :disabled="saveLoading" class="mr10p" @click="submit()">
            提交
          </a-button>
          <!--          <a-button type="primary" :loading="saveLoading" :disabled="submitLoading" class="mr10p"-->
          <!--                    @click="save('DRAFT',false)"-->
          <!--          >-->
          <!--            保存草稿-->
          <!--          </a-button>-->
        </template>
        <BasePrintButton
          v-if="form.id && disabled && !isAudit"
          :before-print-fn="beforePrintFn"
          style="display: inline-block;margin-right: 10px;"
        />
        <a-button v-checkVisibleInDetail @click="$close">关闭</a-button>
      </div>
    </div>
    <person-list
      ref="personList"
      :org-id="form.projectDeptId"
      @getPerson="getPerson"
    />
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import Api from '@/api/material/plan/concreteApply.js'
import SelectPerson from '@/components/Select/SelectPerson'
import part from '@/views/office/assetManagement/check/part'
import BSelect from '@/components/BComponents/BSelect'
import materialDetail from '@/views/materials/plan/concreteApply/components/materialDetail'
import moment from 'moment'
import SelectProject from '@/components/Select/SelectProject'

export default {
  name: 'a' + Date.now(),
  components: {
    SelectPerson,
    part,
    materialDetail
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.disabled = true
        }
      }
    },
    stepVal(newVal, oldVal) {
      this.$set(this.activeKey, newVal, true)
    }
  },
  computed: {
    /*eslint-disable*/
    formConfig() {
      return [
        {
          row: true,
          children: [
            {
              type: 'input', value: 'code', label: '混凝土申请表编码',
              attrs: { disabled: true }
            },
            {
              type: SelectProject,
              value: 'projectId',
              label: '项目名称',
              attrs: {
                isUseChangeEvent:true,
                disabled: this.form.id !== null,
                form: this.form,
                keyValue: 'branchComId'
              },
              on: {
                selectChange: async e => {
                  this.form.projectName = e.name
                  this.form.projectDeptId = e.projectDeptId
                }
              }
            },
            {
              type: BSelect, value: 'materialMonthId', label: '物资需求月计划编码',
              show: this.form.id === null,
              attrs: {
                keys: ['id', 'materialMonthCode'],
                isClear: this.form.id === null,
                init: false,
                form: this.form,
                keyValue: 'projectId',
                // list: this.monthList,
                request: () => Api.getMonthByProjectId({}, { projectId: this.form.projectId })
              }
            },
            {
              type: 'input', value: 'materialMonthCode', label: '物资需求月计划编码',
              show: this.form.id !== null,
              attrs: {
                disabled: true
              }
            },
            {
              type: 'number', value: 'documentCode', label: '单据编号',
              show: !this.disabled
            },
            {
              type: 'number', value: 'documentCodeAll', label: '单据编号',
              show: this.disabled,
              attrs: {
                disabled: true
              }
            },
            {
              type: 'input-search', value: 'contactName', label: '联系人',
              attrs: { disabled: this.disabled },
              on: {
                click: () => {
                  if (this.form.projectId) {
                    this.$refs.personList.open()
                  } else {
                    return this.$noticeWarning('请选择项目名称！')
                  }
                }
              }
            }, {
              type: 'input', value: 'contactPhone', label: '电话',
              attrs: { disabled: true }
            }, {
              type: 'input', value: 'creatorName', label: '创建人',
              attrs: { disabled: true }
            }, {
              type: 'date-picker', value: 'createTime', label: '创建时间',
              attrs: {
                disabled: true,
                valueFormat: 'YYYY-MM-DD'
              }
            }
          ]
        }
      ]
    },
    loading() {
      return this.submitLoading || this.saveLoading
    }
  },
  data() {
    return {
      findFileList: Api.findFileList,
      Api: Api,
      beforePrintFn: async () => {
        let res = await Api.print({ id: this.form.id })
        return res.data.content
      },
      activeKey: [true, false, false, false, false, false, false],
      stepVal: 0,
      monthList: [],
      submitLoading: false,
      saveLoading: false,
      disabled: this.$route.query.detail == 1,
      form: {
        id: null,
        projectDeptId: '',
        materialMonthId: undefined,
        projectId: undefined,
        createTime: moment(Date.now()),
        creatorName: this.$userInfo().name,
        branchComId: this.$currentPost().orgId,
        branchComName: this.$currentPost().orgName
      },
      formRules: {
        documentCode: { required: true, message: '编号不能为空', trigger: 'change' },
        contactName: { required: true, message: '联系人不能为空', trigger: 'change' },
        projectId: { required: true, message: '项目名称不能为空', trigger: 'change' },
        materialMonthId: { required: true, message: '物资需求月计划编码不能为空', trigger: 'change' }
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  created: async function() {
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id
      await this.getBaseInfo()
      if (this.disabled) {
        this.$set(this.activeKey, 2, true)
        this.$set(this.activeKey, 1, true)
      }
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('material_concrete_apply')
  },
  methods: {
    getPerson: function(row) {
      this.form.contactId = row.userId
      this.form.contactName = row.name
      this.form.contactPhone = row.phoneNum
    },

    stepChange(val) {
      if (!this.form.id && !this.isAudit) {
        // 作为审批详情时可跳过步骤
        if (val) {
          this.$message.warning('切换步骤前请先填写基本信息')
          this.stepVal = 0
        }
      } else {
        if (!this.isNext) {
          this.$set(this.activeKey, val, !this.activeKey[val])
          this.stepVal = val
        }
      }
      this.isNext = false
    },
    async getBaseInfo() {
      this.saveLoading = true
      let res = await Api.findListByMainId({}, { id: this.form.id })
      if (res.code === this.SUCCESS_CODE) {
        this.form = res.data
        let res1 = await Api.getMonthByProjectId({}, { projectId: this.form.projectId })
        if (res1.code === this.SUCCESS_CODE) {
          this.monthList = res1.data
        }
      }
      this.saveLoading = false
    },
    async submit() {
       this.setProcessConfig = null;
      if (this.form.id && await this.save('SUBMITTED', true)) {
        //this.$close()
        return 
      } else if (!await this.save('DRAFT', true)) {
        return this.submit()
      }
    },
    async save(auditStatus, isSubmit = false, isNext = false) {
      if (isNext && this.disabled) {
        return this.stepChange(this.stepVal + 1)
      }
      return new Promise(async resolve => {
        let isPass = true
        if (isSubmit) {
          this.$refs.form.validate(valid => {
            isPass = valid
          })
        } else {
          isPass = true
          if (!this.form.projectId) {
            isPass = false
            this.$noticeWarning('请选择项目名称')
          }
          if (!this.form.materialMonthId) {
            isPass = false
            this.$noticeWarning('请选择物资需求月计划编码')
          }
        }
        if (isPass) {
          this.$refs.form.clearValidate()
          let res
          let temp = this.$clone(this.form)
          temp.auditStatus = auditStatus
          if (!isSubmit) {
            this.saveLoading = true
          } else {
            this.submitLoading = true
          }
         this.submitApprovalConfirm(this.isSubmit?this.processConfig:6, async(flag)=>{
            if(!flag) {
              this.loading = false
              return
            }
           if (temp.id) {
            res = await Api.editByMain(temp)
          } else {
            res = await Api.createByMain(temp)
          }
          if (res.code === 200) {
            this.form.id = res.data.id
            await this.getBaseInfo()
            if (auditStatus === 'DRAFT') {
              if (!isSubmit) {
                this.$message.success('保存成功')
              }
              if (isNext) {
                this.stepChange(this.stepVal + 1)
              }
            } else {
              this.$message.success('提交成功')
               //提交时，返回id
              this.businessId = this.form.id;
             this.setProcessConfig = this.processConfig;
            }
            resolve(true)
          }
         })
          this.saveLoading = false
          this.submitLoading = false
        }
      })
    }
  }
}
</script>
